/**
 * 主界面左侧的设备树菜单
 * 根据json数据生成树
 */

DeviceTree = {}
var treeObj="";
var rightMenu;
var setting = {
	check: {
		enable: true
	},
	data: {
		simpleData: {
			enable: true
		}, key: {
			title: "plateNo"
		}
	}, callback: {
		onClick: onClick,
		onCheck: onCheck,
		onRightClick: OnRightClick
	}, view: {
		showTitle: false,
		fontCss: setHighlight // 高亮一定要设置，setHighlight是自定义方法
	}
};

DeviceTree.createTree = function (menu) {
	this.filterParams = {updateNode: false, filter: false}; //过滤条件
	rightMenu = menu;
	this.treeManager = $("#deviceTree");
	this.load();

	var ref = setInterval(function() {
	// 	//定时更新设备节点的状态
	// 	me.load(true); //更新模式
		if(DeviceTreeIds!='') {
			var datas = {ids: DeviceTreeIds};
			$.ajax({
				type: "get",
				url: '/sys/updateTree',
				data: datas,
				success: function (result) {
					DeviceTree.updateNode(result);
					add_control(MyMap.getMapHandler().map);
				}
			});
			$.ajax({
				type: 'get',
				url: '/sys/updateRealData',
				data: datas,
				success: function (result) {
					MyMap.createMarkerByGpsData(result);
				}
			})
		}
	},30000);
}

var selectDeviceIds = "";
var devSet = new Set();
function onCheck(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("deviceTree"), nodes = zTree.getCheckedNodes(true);
	selectDeviceIds = "";
	if (treeNode.checked) {
		if (nodes && nodes.length) {
			for (var i = 0, len = nodes.length; i < len; i++) {
				var node = nodes[i];
				if (typeof (node.children) == "undefined" && node.id.indexOf("d") == 0) {
					var deviceId = node.id.substring(2, node.id.length);
					devSet.add(deviceId);
				}
			}
		}
	} else {
		nodes = zTree.getCheckedNodes(false);
		for (var i = 0, len = nodes.length; i < len; i++) {
			var node = nodes[i];
			if (typeof (node.children) == "undefined" && node.id.indexOf("d") == 0 && !node.checked) {
				var deviceId = node.id.substring(2, node.id.length);
				devSet.delete(deviceId);
			}
		}
	}
	DeviceTree.register();
}



function OnRightClick(event, treeId, treeNode) {
	var items = rightMenu;
	console.log(items);
	if (typeof (items) != "undefined") {
		if (items.length > 0) {
			var zTree = $.fn.zTree.getZTreeObj("deviceTree");
			zTree.selectNode(treeNode);
			if (!treeNode.isParent && treeNode.id.indexOf("d") == 0) {
				rightMenu.menu('show', {
					left: event.pageX,
					top: event.pageY,
				});
			}

		}
	}
}

DeviceTree.load = function () {
	var me = this;
	var url = "/sys/tree";
	$.ajax({
		type: "POST",
		url: url,
		data: this.filterParams,
		error: function () {},
		success: function (data) {
			me.initializeCallback(data); //填充到树中，生成设备数
			var treeObj = $.fn.zTree.getZTreeObj("deviceTree");
			var nodes = treeObj.getNodes();
			if (nodes.length > 0) {
				for (var i = 0; i < nodes.length; i++) {
					treeObj.expandNode(nodes[i], true, false, false);
				}
			}
		}
	});

}

/**
 * 订阅要实时查看的设备数据
 */
DeviceTree.register = function () {
	var url = "/sys/tree";
	selectDeviceIds = "";
	for(var element of devSet)
	{
		selectDeviceIds += element+",";
	};
	if (selectDeviceIds != "") {
		selectDeviceIds = selectDeviceIds.substring(0, selectDeviceIds.length - 1);
	}
	DeviceTreeIds = selectDeviceIds;
	var datas = {ids: DeviceTreeIds};
	$.ajax({
		type: "get",
		url:'/sys/updateTree',
		data:datas,
		success: function (result) {
			DeviceTree.updateNode(result);
			add_control(MyMap.getMapHandler().map);
		}
	});
	$.ajax({
		type:'get',
		url:'/sys/updateRealData',
		data:datas,
		success: function (result) {
			MyMap.createMarkerByGpsData(result);
		}
	});
}

DeviceTree.updateNode = function (result) {
	var zTree = $.fn.zTree.getZTreeObj("deviceTree");
	for (var i = 0; i < result.length; i++) {
		var node = zTree.getNodeByParam("id", result[i].id,null);
		node.name = result[i].name;
		node.icon = result[i].icon;
		zTree.updateNode(node);
	}
}


/**
 * 用于在获取数据后，填充设备树
 */
DeviceTree.initializeCallback = function (data) {
	treeObj = $.fn.zTree.init($("#deviceTree"), setting, data);
}

DeviceTree.getSelectNode = function () {
	var treeObj = $.fn.zTree.getZTreeObj("deviceTree");
	var sNodes = treeObj.getSelectedNodes();
	var node;
	if (sNodes.length > 0) {
		node = sNodes[0];
	}

	return node;
}

/**
 tree的onclick事件
 */
function onClick(e, treeId, node) {
	//如果是叶子节点，表明点击的是设备
	if (typeof (node.children) == "undefined" && node.id.indexOf("d") == 0) {
		var deviceId = node.id.substring(2, node.id.length);
		var datas = {"devid":deviceId};
		$.ajax({
			type:'get',
			url:'/sys/findByDevid',
			data:datas,
			success: function (result) {
				MyMap.getMapHandler().showMarker(result);
			}
		})
	}
}

// 有输入后定时执行一次，如果上次的输入还没有被执行，那么就取消上一次的执行
var timeoutId = null;
DeviceTree.Treefilter = function (filterType, value) {
	if (value == null || $.trim(value) == "") {
		$.iMessager.alert('提示', '请输入查询内容', 'messager-warning');
	}
	if (timeoutId) {
		clearTimeout(timeoutId);
	}
	timeoutId = setTimeout(function () {
		searchNode(filterType, value);
	}, 500);

}

//精确搜索
function searchNode(filterType, value) {
	if (value == "") return;
	//搜索设备号
	if (filterType == 0) {
		// 获取与value匹配的节点，使用的ztreeAPI getNodesByParam
		var nodes = treeObj.getNodesByParam("plateNo", $.trim(value));
		if (nodes.length > 0) {
			for (var i = 0; i < nodes.length; i++) {
				if (nodes[i].id.indexOf("d") == 0) {
					treeObj.selectNode(nodes[i]);
					$("#"+nodes[i].tId+"_a").click();
					break;
				}
			}
		} else {
			treeObj.cancelSelectedNode();
		}
	}

}

// 设置高亮字体
function setHighlight(treeId, treeNode) {
	return (!!treeNode.highlight) ? {color: "#A60000", "font-weight": "bold"} : {
		color: "#333",
		"font-weight": "normal"
	};
}